package com.elinkway.infinitemovies.dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;

import com.elinkway.infinitemovies.bean.AlbumUpdateInfoBean;
import com.elinkway.infinitemovies.bean.PlayRecord;
import com.elinkway.infinitemovies.utils.LogUtils;
import com.elinkway.infinitemovies.utils.MoviesConstant;

import java.util.ArrayList;
import java.util.List;

public class PlayRecordDao extends BaseDao<PlayRecord> {

    private static final String TABLE_NAME = "play_record";
    private static final String FIELD_ID = "id";
    private static final String FIELD_NAME = "name";
    private static final String FIELD_TIME = "time";
    private static final String FIELD_URL = "url";
    private static final String FIELD_AID = "aid";
    private static final String FIELD_EPISODE = "episode";
    private static final String FIELD_VT = "vt";
    private static final String FIELD_CATEGORYNAME = "category_name";
    private static final String FIELD_SEEKHISTORY = "seekHistory";
    private static final String FIELD_PORDER = "porder";
    private static final String FIELD_SITE = "site";
    private static final String FIELD_REQUEST_TYPE = "request_type";
    private static final String FIELD_VID = "vid";
    private static final String FIELD_IS_UPLOAD = "is_upload";
    private static final String FIELD_POSTER = "poster";
    private static final String PAGE_INDEX = "page_index";
    private static final String CURRENT_PAGE_POSITION = "current_page_position";

    public PlayRecordDao(Context context) {
        super(context);
    }

    @Override
    public synchronized void delete(final String aid) {
        doInBackground(new Runnable() {

            @Override
            public void run() {
                SQLiteDatabase db = safelyGetDataBase();
                LogUtils.e("save", String.format("delete from %s where %s='%s'", TABLE_NAME, FIELD_AID, aid));
                db.execSQL(String.format("delete from %s where %s='%s'", TABLE_NAME, FIELD_AID, aid));
                safelyCloseDataBase();
            }

        });
    }

    @Override
    public synchronized void delAll() {

    }

    public synchronized List<PlayRecord> getAll() {
        List<PlayRecord> list = new ArrayList<PlayRecord>();
        SQLiteDatabase db = safelyGetDataBase();
        Cursor cursor = db.rawQuery("select * from " + TABLE_NAME + " order by id DESC", null);
        while (cursor.moveToNext()) {
            PlayRecord record = new PlayRecord();
            record.setAid(cursor.getString(1));
            record.setName(cursor.getString(2));
            record.setTime(cursor.getLong(4));
            record.setUrl(cursor.getString(3));
            record.setEpisodeName(cursor.getString(5));
            record.setVt(cursor.getString(6));
            record.setCategoryName(cursor.getString(7));
            record.setSeekHistory(cursor.getLong(8));
            record.setPorder(cursor.getString(9));
            record.setSite(cursor.getString(10));
            record.setRequestType(cursor.getString(11));
            record.setVid(cursor.getString(12));
            record.setIsUpload(cursor.getString(13));
            record.setPoster(cursor.getString(14));
            record.setPageIndex(cursor.getInt(15));
            record.setCurrentPagePosition(cursor.getInt(16));
            list.add(record);
        }
        safelyCloseDataBase();
        cursor.close();
        return list;
    }

    @Override
    public synchronized void save(final PlayRecord bean) {
        if (TextUtils.isEmpty(bean.getAid())) {
            return;
        }

        doInBackground(new Runnable() {

            @Override
            public void run() {
                SQLiteDatabase db = safelyGetDataBase();
                LogUtils.e("save", "saving " + bean.getAid());
                db.execSQL(String.format("delete from %s where %s='%s'", TABLE_NAME, FIELD_AID, bean.getAid()));
                Cursor cursor = db.rawQuery(String.format("Select * from %s;", TABLE_NAME), null);
                if (cursor.getCount() == MoviesConstant.PLAY_RECORD_MAXIMUM_SIZE) {
                    db.execSQL("delete from " + TABLE_NAME + " where " + FIELD_ID + "=(select min(" + FIELD_ID + ") from " + TABLE_NAME + ")");
                }
                ContentValues values = new ContentValues();
                values.put(FIELD_AID, bean.getAid());
                values.put(FIELD_NAME, bean.getName());
                values.put(FIELD_URL, bean.getUrl());
                values.put(FIELD_TIME, System.currentTimeMillis());
                values.put(FIELD_EPISODE, bean.getEpisode());
                values.put(FIELD_VT, bean.getVt());
                values.put(FIELD_CATEGORYNAME, bean.getCategoryName());
                values.put(FIELD_SEEKHISTORY, bean.getSeekHistory());
                values.put(FIELD_PORDER, bean.getPorder());
                values.put(FIELD_SITE, bean.getSite());
                values.put(FIELD_REQUEST_TYPE, bean.getRequestType());
                values.put(FIELD_VID, bean.getVid());
                values.put(FIELD_IS_UPLOAD, bean.getIsUpload());
                values.put(FIELD_POSTER, bean.getPoster());
                values.put(PAGE_INDEX, bean.getPageIndex());
                values.put(CURRENT_PAGE_POSITION, bean.getCurrentPagePosition());
                db.insert(TABLE_NAME, null, values);
                safelyCloseDataBase();
                cursor.close();
            }

        });
    }

    public synchronized PlayRecord getByAid(String aid) {
        PlayRecord record = new PlayRecord();
        SQLiteDatabase db = safelyGetDataBase();
        Cursor cursor = db.rawQuery("select * from " + TABLE_NAME + " where " + FIELD_AID + "='" + aid + "'", null);
        if (cursor.getCount() == 0) {
            safelyCloseDataBase();
            cursor.close();
            return null;
        }
        cursor.moveToNext();
        record.setAid(cursor.getString(1));
        record.setName(cursor.getString(2));
        record.setTime(cursor.getLong(4));
        record.setUrl(cursor.getString(3));
        record.setEpisodeName(cursor.getString(5));
        record.setVt(cursor.getString(6));
        record.setCategoryName(cursor.getString(7));
        record.setSeekHistory(cursor.getLong(8));
        record.setPorder(cursor.getString(9));
        record.setSite(cursor.getString(10));
        record.setRequestType(cursor.getString(11));
        record.setVid(cursor.getString(12));
        record.setIsUpload(cursor.getString(13));
        record.setPoster(cursor.getString(14));
        record.setPageIndex(cursor.getInt(15));
        record.setCurrentPagePosition(cursor.getInt(16));
        safelyCloseDataBase();
        cursor.close();
        return record;
    }

    public synchronized void save(final List<PlayRecord> playRecordList) {
        if (playRecordList == null || playRecordList.size() == 0) {
            return;
        }
        doInBackground(new Runnable() {

            @Override
            public void run() {
                SQLiteDatabase db = safelyGetDataBase();
                Cursor cursor = db.rawQuery(String.format("Select * from %s;", TABLE_NAME), null);
                PlayRecord bean = null;
                for (int i = playRecordList.size() - 1; i >= 0; i--) {
                    bean = playRecordList.get(i);
                    if (bean != null) {
                        if (TextUtils.isEmpty(bean.getAid())) {
                            continue;
                        }
                        db.execSQL(String.format("delete from %s where %s='%s'", TABLE_NAME, FIELD_AID, bean.getAid()));
                        if (cursor.getCount() == MoviesConstant.PLAY_RECORD_MAXIMUM_SIZE) {
                            db.execSQL("delete from " + TABLE_NAME + " where " + FIELD_ID + "=(select min(" + FIELD_ID + ") from " + TABLE_NAME + ")");
                        }
                        ContentValues values = new ContentValues();
                        values.put(FIELD_AID, bean.getAid());
                        values.put(FIELD_NAME, bean.getName());
                        values.put(FIELD_URL, bean.getUrl());
                        values.put(FIELD_TIME, bean.getTime());
                        values.put(FIELD_EPISODE, bean.getEpisode());
                        values.put(FIELD_VT, bean.getVt());
                        values.put(FIELD_CATEGORYNAME, bean.getCategoryName());
                        values.put(FIELD_SEEKHISTORY, bean.getSeekHistory());
                        values.put(FIELD_PORDER, bean.getPorder());
                        values.put(FIELD_SITE, bean.getSite());
                        values.put(FIELD_REQUEST_TYPE, bean.getRequestType());
                        values.put(FIELD_VID, bean.getVid());
                        values.put(FIELD_IS_UPLOAD, bean.getIsUpload());
                        values.put(FIELD_POSTER, bean.getPoster());
                        values.put(PAGE_INDEX, bean.getPageIndex());
                        values.put(CURRENT_PAGE_POSITION, bean.getCurrentPagePosition());
                        db.insert(TABLE_NAME, null, values);
                    }
                }
                safelyCloseDataBase();
                cursor.close();
            }
        });
    }

    public synchronized List<PlayRecord> getLocalAll() {
        List<PlayRecord> list = new ArrayList<>();
        SQLiteDatabase db = safelyGetDataBase();
        Cursor cursor = db.rawQuery("select * from " + TABLE_NAME + " where " + FIELD_IS_UPLOAD + "='" + 0 + "'" + " order by id DESC", null);
        while (cursor.moveToNext()) {
            PlayRecord record = new PlayRecord();
            record.setAid(cursor.getString(1));
            record.setName(cursor.getString(2));
            record.setTime(cursor.getLong(4));
            record.setUrl(cursor.getString(3));
            record.setEpisodeName(cursor.getString(5));
            record.setVt(cursor.getString(6));
            record.setCategoryName(cursor.getString(7));
            record.setSeekHistory(cursor.getLong(8));
            record.setPorder(cursor.getString(9));
            record.setSite(cursor.getString(10));
            record.setRequestType(cursor.getString(11));
            record.setVid(cursor.getString(12));
            record.setIsUpload(cursor.getString(13));
            record.setPoster(cursor.getString(14));
            record.setPageIndex(cursor.getInt(15));
            record.setCurrentPagePosition(cursor.getInt(16));
            list.add(record);
        }
        safelyCloseDataBase();
        cursor.close();
        return list;
    }

    public synchronized void deleteServerAll() {
        doInBackground(new Runnable() {

            @Override
            public void run() {
                SQLiteDatabase db = safelyGetDataBase();
                db.execSQL(String.format("delete from %s where %s='%s'", TABLE_NAME, FIELD_IS_UPLOAD, 1));
                safelyCloseDataBase();
            }

        });
    }

    public synchronized List<PlayRecord> selectFromServer(int number) {
        List<PlayRecord> list = new ArrayList<>();
        SQLiteDatabase db = safelyGetDataBase();
        Cursor cursor = db.rawQuery("select * from " + TABLE_NAME + " where " + FIELD_IS_UPLOAD + "='" + 1 + "' order by id DESC", null);
        int i = 0;
        while (cursor.moveToNext() && i < number) {
            PlayRecord record = new PlayRecord();
            record.setAid(cursor.getString(1));
            record.setName(cursor.getString(2));
            record.setTime(cursor.getLong(4));
            record.setUrl(cursor.getString(3));
            record.setEpisodeName(cursor.getString(5));
            record.setVt(cursor.getString(6));
            record.setCategoryName(cursor.getString(7));
            record.setSeekHistory(cursor.getLong(8));
            record.setPorder(cursor.getString(9));
            record.setSite(cursor.getString(10));
            record.setRequestType(cursor.getString(11));
            record.setVid(cursor.getString(12));
            record.setIsUpload(cursor.getString(13));
            record.setPoster(cursor.getString(14));
            record.setPageIndex(cursor.getInt(15));
            record.setCurrentPagePosition(cursor.getInt(16));
            list.add(record);
            i++;
        }
        safelyCloseDataBase();
        cursor.close();
        return list;
    }

    public synchronized void batchDelete(final List<PlayRecord> playRecordList) {
        if (playRecordList == null) {
            return;
        }
        doInBackground(new Runnable() {

            @Override
            public void run() {
                SQLiteDatabase db = safelyGetDataBase();
                for (int i = 0; i < playRecordList.size(); i++) {
                    if (playRecordList.get(i) != null && !TextUtils.isEmpty(playRecordList.get(i).getAid())) {
                        db.execSQL(String.format("delete from %s where %s='%s'", TABLE_NAME, FIELD_AID, playRecordList.get(i).getAid()));
                    }
                }
                safelyCloseDataBase();
            }

        });
    }

    public synchronized List<String> getNoPosterAidList() {
        List<PlayRecord> list = getAll();
        List<String> aidList = new ArrayList<>();
        for (PlayRecord record : list) {
            if (record != null) {
                if (TextUtils.isEmpty(record.getPoster())) {
                    aidList.add(record.getAid());
                }
            }
        }
        return aidList;
    }

    /**
     * 更新图片，
     *
     * @param bean
     */
    public void updatePosters(final AlbumUpdateInfoBean bean) {
        doInBackground(new Runnable() {

            @Override
            public void run() {
                SQLiteDatabase db = safelyGetDataBase();
                ContentValues values = new ContentValues();
                values.put(FIELD_POSTER, bean.getPoster());
                String[] where = {bean.getAid()};
                db.update(TABLE_NAME, values, "aid=?", where);
                safelyCloseDataBase();
            }

        });
    }

}
